package com.xiaotao.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.util.Map;

public class JwtUtil {
    public static final String secretString ="token!Q2W#E$RWtoken!Q2W#E$RWtoken!Q2W#E$RW";

    public static String getToken(Map map) throws Exception{
        //1.生成头
        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT).build();
        //2.生成荷载
        Payload payload = new Payload(map);
        //3.生成签名器
        MACSigner macSigner = new MACSigner(secretString);
        //4.生成jws对象（签名部分）
        JWSObject jwsObject = new JWSObject(header, payload);
        //5.生成签名
        jwsObject.sign(macSigner);
        String token = jwsObject.serialize();//序列化签名
        return token;
    }

    public static Boolean verify(String jwt) throws Exception{
        JWSObject parse = JWSObject.parse(jwt);//解析jwt
        //验证是否合法
        MACVerifier verifier = new MACVerifier(secretString);
        boolean verify = parse.verify(verifier);
        return verify;
    }

    public static Map getPayload(String jwt) throws Exception{
        //解析jwt
        JWSObject jwsObject = JWSObject.parse(jwt);
        //获得荷载
        Payload payload = jwsObject.getPayload();
        //转化成json对象
        Map<String, Object> map = payload.toJSONObject();
        return map;
    }

    public static Integer getUserId(String jwt) throws Exception {
        //解析jwt
        JWSObject jwsObject = JWSObject.parse(jwt);
        //获得荷载
        Payload payload = jwsObject.getPayload();
        //转化成json对象
        Map<String, Object> map = payload.toJSONObject();
         return  Integer.parseInt(map.get("userId").toString());
    }
}
